package com.wenx.concurrent;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 并发同步器--独占模式
 * 银行窗口同步类
 * Created by wenx on 2019-10-09 14:01
 */
public class BankServiceWindow {

    private final MySync sync;

    public BankServiceWindow() {
        this.sync = new MySync();
    }

    private static class MySync extends AbstractQueuedSynchronizer {

        @Override
        public boolean tryAcquire(int acquire) {
               if(super.compareAndSetState(0,1)) {
                   super.setExclusiveOwnerThread(Thread.currentThread());
                   return true;
               }
               return false;
        }

        @Override
        protected boolean tryRelease(int release) {
            if(getState() == 0)
                throw new IllegalMonitorStateException();
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }
    }


    public void handle() {
        sync.acquire(1);
    }

    public void unHandle() {
        sync.release(1);
    }
}